package summer.hot100.v1;

import java.util.LinkedList;
import java.util.List;

public class Solution22 {
    List<String> res = new LinkedList<>();

    StringBuilder sb = new StringBuilder();

    public List<String> generateParenthesis(int n) {
        backtrack(n, n);
        return res;
    }

    public void backtrack(int left, int right) {
        if (left == 0 && right == 0) {
            res.add(sb.toString());
            return;
        }
        if (left > right) return;
        if (left > 0) {
            sb.append('(');
            backtrack(left - 1, right);
            sb.deleteCharAt(sb.length() - 1);
        }
        if (right > 0) {
            sb.append(')');
            backtrack(left, right - 1);
            sb.deleteCharAt(sb.length() - 1);
        }
    }
}
